import os
import json
from typing import Dict
import dearpygui.dearpygui as dpg


class DoctorTab:
    def __init__(self, doctors: Dict[str, Dict] = {}, tag=0, label="医生"):
        self.label = label
        self.doctors = doctors
        self.titles = {"post": "岗位", "group": "分组"}
        self.options = {"post": set(), "group": set()}
        self.load_doctors()
        with dpg.tab(tag=tag, label=label) as tab:
            self.tag = tab
            dpg.add_table(
                tag=f"{tab}_table",
                # row_background=True,
                borders_outerH=True,
                borders_outerV=True,
                borders_innerH=True,
                borders_innerV=True,
            )
        self.update_table()

    def load_doctors(self, filename="doctors.json"):
        if not os.path.exists(filename):
            return
        with open(filename, "r", encoding="utf-8") as file:
            data = json.load(file)
            self.doctors.clear()
            for key in data:
                val = data[key]
                doctor = {}
                for k in self.titles:
                    doctor[k] = val.get(k, "")
                self.doctors[key] = doctor
            # self.doctors = json.load(file)
            self.update_options()

    def save_doctors(self, filename="doctors.json"):
        with open(filename, "w", encoding="utf-8") as file:
            json.dump(self.doctors, file, indent=2, ensure_ascii=False)

    def add_doctor(self, sender, app_data, user_data):
        if app_data not in self.doctors:
            self.doctors[app_data] = {}
            self.save_doctors()
            self.load_doctors()
            self.update_table()

    def del_doctor(self, sender, app_data, user_data):
        dpg.hide_item(dpg.get_item_parent(sender))
        if user_data in self.doctors:
            del self.doctors[user_data]
            self.save_doctors()
            self.load_doctors()
            self.update_table()

    def mov_doctor(self, sender, name):
        to = dpg.get_item_user_data(sender)
        if name == to:
            return
        doctor = self.doctors.pop(name)
        data = self.doctors.copy()
        self.doctors.clear()
        for key, val in data.items():
            self.doctors[key] = val
            if key == to:
                self.doctors[name] = doctor
        self.save_doctors()
        self.load_doctors()
        self.update_table()

    def change_option(self, sender, app_data, user_data):
        name, key = user_data
        if self.doctors[name].get(key, "") != app_data.strip():
            self.doctors[name][key] = app_data.strip()
            self.save_doctors()
            self.load_doctors()
            self.update_table()

    def update_options(self):
        for key in self.options:
            self.options[key].clear()
        for name in self.doctors:
            doctor = self.doctors[name]
            for key in self.options:
                if key in doctor:
                    val = doctor[key].strip()
                    if val:
                        self.options[key].add(val)

    def update_table(self):
        name = f"{self.tag}_table"
        dpg.delete_item(name, children_only=True)
        dpg.add_table_column(
            parent=name, label="姓名", width_fixed=True, init_width_or_weight=100
        )
        for key in self.titles:
            dpg.add_table_column(parent=name, label=self.titles[key])
        for key, doctor in self.doctors.items():
            with dpg.table_row(parent=name):
                with dpg.group(
                    payload_type="rows", drop_callback=self.mov_doctor, user_data=key
                ):
                    with dpg.drag_payload(drag_data=key, payload_type="rows"):
                        dpg.add_text(key)
                    # dpg.add_text(key + " " * 10)
                    dpg.add_button(label=key, enabled=False, width=-1)
                    with dpg.popup(dpg.last_item(), min_size=(0, 0)):
                        dpg.add_button(
                            label="删除",
                            width=50,
                            user_data=key,
                            callback=self.del_doctor,
                        )
                for k in self.options:
                    with dpg.group(horizontal=True, horizontal_spacing=0):
                        dpg.add_input_text(
                            width=-25,
                            on_enter=True,
                            default_value=doctor[k],
                            callback=self.change_option,
                            user_data=(key, k),
                        )
                        dpg.add_combo(
                            list(self.options[k]),
                            no_preview=True,
                            default_value=doctor[k],
                            callback=self.change_option,
                            user_data=(key, k),
                        )
        with dpg.table_row(parent=name):
            dpg.add_input_text(
                hint="新建",
                width=-1,
                on_enter=True,
                callback=self.add_doctor,
                payload_type="rows",
                drop_callback=lambda s, a: self.del_doctor(s, None, a),
            )
            dpg.add_text("输入框中回车后保存")
            dpg.add_text("输入框中回车后保存")
